/*******************************************************/
/* file: ports.c                                       */
/* abstract:  This file contains the routines to       */
/*            output values on the JTAG ports, to read */
/*            the TDO bit, and to read a byte of data  */
/*            from the prom                            */
/*                                                     */
/*******************************************************/
#include "ports.h"


#include <nds/arm9/console.h> //basic print funcionality

#define V_SRAM ((volatile unsigned char*)0x0A000000)

//BYTE *xsvf_data=0;

//#include "idcheck_xsvf.h"
//#include "rled_xsvf.h"
//#include "gled_xsvf.h"

//int xptr = 0;

short tms_val = 1;
short tdi_val = 0;
short tdo_val;


/* if in debugging mode, then just set the variables */
void setPort(short p,short val)
{

//	iprintf("=%02X %02X", p, val);

	if (p==TMS) {
		tms_val=val;
	}

	if (p==TDI) {
		tdi_val=val;
	}

	if (p==TCK) {
		if (val==0) {
			if (tms_val) {
				if (tdi_val) {
					tdo_val=V_SRAM[0xC000] & 0x01;
				} else {
					tdo_val=V_SRAM[0x8000] & 0x01;
				}

			} else {
				if (tdi_val) {
					tdo_val=V_SRAM[0x4000] & 0x01;
				} else {
					tdo_val=V_SRAM[0x0000] & 0x01;
				}
			}

		}
	}
}


/* read in a byte of data from the prom */
//void readByte(unsigned char *data) {}

/* read the TDO bit from port */
unsigned char readTDOBit()
{
	return tdo_val;

}




/* Wait at least the specified number of microsec.                           */
/* Use a timer if possible; otherwise estimate the number of instructions    */
/* necessary to be run based on the microcontroller speed.  For this example */
/* we pulse the TCK port a number of times based on the processor speed.     */
void waitTime(long microsec)
{
//    static long tckCyclesPerMicrosec    = 1;
//    long        tckCycles   = microsec * tckCyclesPerMicrosec;

    long        tckCycles   = microsec;
    long        i;

    /* For systems with TCK rates >= 1 MHz;  This implementation is fine. */
    for ( i = 0; i < tckCycles; ++i )
    {
        setPort(TCK, 1);
        setPort(TCK, 0);
    }






}
